package com.sp.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sp.model.dto.EmployeeDTO;
import com.sp.model.entity.Employee;
import com.sp.model.entity.PageResult;
import com.sp.model.entity.Result;
import com.sp.model.vo.EmployeeRoleVO;
import com.sp.model.vo.EmployeeVO;
import com.sp.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.sp.constant.EmployeeMessageConstant.*;

/**
 * @author tong
 */
@Api(tags = "管理员管理api接口")
@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<EmployeeVO> login(
            @ApiParam(name = "params", value = "登录参数") @RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        String checkCode = params.get("checkCode");
        String checkCodeId = params.get("checkCodeId");

        Employee employee = employeeService.login(username, password, checkCode, checkCodeId);
        if (employee != null) {
            EmployeeVO employeeVO = BeanUtil.copyProperties(employee, EmployeeVO.class);

            employeeVO.setRoles(BeanUtil.copyToList(employee.getRoles(), EmployeeRoleVO.class));

            return Result.success(EMPLOYEE_LOGIN_SUCCESS, employeeVO);
        }

        return Result.error(EMPLOYEE_LOGIN_FAIL);
    }

    @ApiOperation("token续期，两个token同时刷新")
    @PostMapping("/refreshToken")
    public Result<Map<String, String>> refreshToken(
            @ApiParam(name = "params", value = "token刷新所需参数") @RequestBody Map<String, String> params) {
        String username = params.get("username");
        String refreshToken = params.get("refreshToken");

        return Result.success(TOKEN_REFRESH_SUCCESS, employeeService.refreshToken(username, refreshToken));
    }

    @GetMapping("/logout")
    public Result<Object> logout() {
        if (employeeService.logout()) {
            return Result.success(EMPLOYEE_LOGOUT_SUCCESS);
        }
        return Result.error(EMPLOYEE_LOGOUT_FAIL);
    }

    @ApiOperation("新增管理员信息")
    @PreAuthorize("hasAnyAuthority('employee:add')")
    @PostMapping
    public Result<Object> addEmployee(
            @ApiParam(name = "employeeDTO", value = "管理员信息") @RequestBody EmployeeDTO employeeDTO) {
        if (employeeService.addEmployee(employeeDTO)) {
            if (StrUtil.isBlank(employeeDTO.getPassword())) {
                return Result.success(ADD_EMPLOYEE_SUCCESS + "：密码为空，已设置默认密码");
            }
            return Result.success(ADD_EMPLOYEE_SUCCESS);
        }
        return Result.error(ADD_EMPLOYEE_FAIL);
    }

    @ApiOperation("（批量）删除管理员信息")
    @PreAuthorize("hasAnyAuthority('employee:delete')")
    @DeleteMapping("/{ids}")
    public Result<Object> deleteEmployee(
            @ApiParam(name = "ids", value = "管理员ids") @PathVariable("ids") List<Integer> ids) {
        if (employeeService.deleteEmployees(ids)) {
            return Result.success(DELETE_EMPLOYEE_SUCCESS);
        }
        return Result.error(DELETE_EMPLOYEE_FAIL);
    }

    @ApiOperation("修改管理员信息")
    @PreAuthorize("hasAnyAuthority('employee:update')")
    @PutMapping
    public Result<String> updateEmployee(
            @ApiParam(name = "employeeDTO", value = "管理员信息") @RequestBody EmployeeDTO employeeDTO) {
        if (employeeService.updateEmployee(employeeDTO)) {
            return Result.success(UPDATE_EMPLOYEE_SUCCESS);
        }
        return Result.error(UPDATE_EMPLOYEE_FAIL);
    }

    @ApiOperation("修改个人信息")
    @PutMapping("/me")
    public Result<String> updateMe(
            @ApiParam(name = "employeeDTO", value = "管理员信息") @RequestBody EmployeeDTO employeeDTO) {
        if (employeeService.updateMe(employeeDTO)) {
            return Result.success(UPDATE_EMPLOYEE_SUCCESS);
        }
        return Result.error(UPDATE_EMPLOYEE_FAIL);
    }

    @ApiOperation("修改个人密码")
    @PutMapping("/password")
    public Result<String> updatePassword(
            @ApiParam(name = "employeeDTO", value = "管理员信息") @RequestBody EmployeeDTO employeeDTO) {
        if (employeeService.updatePassword(employeeDTO)) {
            if (StrUtil.isBlank(employeeDTO.getPassword())) {
                return Result.success(UPDATE_EMPLOYEE_SUCCESS + "：密码为空，已设置默认密码");
            }
            return Result.success(UPDATE_EMPLOYEE_SUCCESS);
        }
        return Result.error(UPDATE_EMPLOYEE_FAIL);
    }

    @ApiOperation(value = "根据id查询员工数据", notes = "用于修改员工数据时，回显数据")
    @GetMapping("/{id}")
    public Result<EmployeeVO> selectById(@PathVariable("id") Integer id) {
        // 用处不大，前端未使用
        Employee employee = employeeService.selectById(id);
        if (employee != null) {
            EmployeeVO employeeVO = BeanUtil.copyProperties(employee, EmployeeVO.class);

            employeeVO.setRoles(BeanUtil.copyToList(employee.getRoles(), EmployeeRoleVO.class));

            return Result.success(SELECT_EMPLOYEE_SUCCESS, employeeVO);
        }
        return Result.error(SELECT_EMPLOYEE_FAIL);
    }

    @ApiOperation("条件查询管理员信息")
    @GetMapping("/page")
    public Result<PageResult<EmployeeVO>> page(@ApiParam(name = "currentPage", value = "页码") Integer currentPage,
                                               @ApiParam(name = "pageSize", value = "每页条数") Integer pageSize,
                                               @ApiParam(name = "employeeDTO", value = "管理员信息") EmployeeDTO employeeDTO) {
        IPage<Employee> pages = employeeService.page(currentPage, pageSize, employeeDTO);
        if (pages != null) {
            List<Employee> employees = pages.getRecords();

            List<EmployeeVO> employeeVOS = new ArrayList<>();
            for (Employee employee : employees) {
                EmployeeVO employeeVO = BeanUtil.copyProperties(employee, EmployeeVO.class);

                employeeVO.setRoles(BeanUtil.copyToList(employee.getRoles(), EmployeeRoleVO.class));
                employeeVOS.add(employeeVO);
            }

            return Result.success(SELECT_EMPLOYEE_SUCCESS
                    , new PageResult<>(pages.getSize(), pages.getTotal(), pages.getCurrent(), pages.getPages(), employeeVOS));
        }
        return Result.error(SELECT_EMPLOYEE_FAIL);
    }

    @ApiOperation("生成验证码图片")
    @GetMapping("/checkCode")
    public Result<Map<String, Object>> getCheckCode(@ApiParam(name = "checkCodeId", value = "验证码id") String checkCodeId) {
        // checkCodeId不为null时，是切换，删除旧验证码
        if (checkCodeId != null) {
            employeeService.removeCheckCode(checkCodeId);
        }

        Map<String, Object> checkCode = employeeService.generateCheckCode(4, 8);
        if (checkCode != null && checkCode.size() == 2) {
            return Result.success(LOGIN_CHECKCODE_SUCCESS, checkCode);
        }
        return Result.error(LOGIN_CHECKCODE_FAIL);
    }

}
